package com.gec.filter;

import com.gec.common.MyFailureHandler;
import com.gec.common.VerificationException;
import com.gec.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class VerificationCodeFilter extends OncePerRequestFilter {

    private MyFailureHandler failureHandler = new MyFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String uri = request.getRequestURI();
        if (!"/login".equals(uri)) {
            //不是登录操作.过滤器正常执行
            filterChain.doFilter(request, response);
        } else {
            log.info("VerificationCodeFilter----doFilterInternal");
            try {
                verify(request);

                filterChain.doFilter(request, response);
            } catch (VerificationException e) {
                //发生异常交给验证失败处理器处理
                Result result = new Result();
                result.setCode(1);
                result.setCode(1002);
                result.setMsg("验证码错误!!!");
                failureHandler.setResult(result);
                failureHandler.onAuthenticationFailure(request, response, e);
            }
        }
    }

    private void verify(HttpServletRequest request) {
        //获取页面输入的验证码
        String codeText = request.getParameter("codeText");
        //获取系统生成的验证码
        Object code = request.getSession().getAttribute("code");

        String sessionCode = "";

        if (code != null) {
            sessionCode = (String) code;
        }

        log.info("VerificationCodeFilter----doFilterInternal---code:{}", sessionCode);

        //处理逻辑
        if (!StringUtils.isEmpty(sessionCode)) {
            //移除session中的code
            request.getSession().removeAttribute("code");
        }

        if (StringUtils.isEmpty(codeText) || StringUtils.isEmpty(sessionCode) || !codeText.equalsIgnoreCase(sessionCode)) {
            throw new VerificationException();
        }
    }
}
